package com.lucksoft.TempMonitor.ui;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

public class HisDataPanel extends JPanel implements Runnable {
    private JFrame mainUI;

    private TableModel dataModel;
    private JScrollPane scrollpane;
    private JTable table;

    public HisDataPanel(JFrame mainUI) {
        super();
        this.mainUI = mainUI;
        this.setBackground(Color.green);
        this.setLayout(new BorderLayout());
        //设置表格列名

        Vector CellsVector = new Vector();
        Vector TitleVector = new Vector();
        TitleVector.add("序号");
        TitleVector.add("采集时间");
        TitleVector.add("字段1");
        TitleVector.add("字段2");
        TitleVector.add("字段3");

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//小写的mm表示的是分钟
        Date date=new Date();
        for (int i=0;i<1000;i++) {
            Vector v = new Vector();
            v.add(i+1);
            date = new Date(date.getTime()+i*10000);
            v.add(sdf.format(date));
            v.add("数值1-"+i);
            v.add("数值2-"+i);
            v.add("数值3-"+i);
            CellsVector.add(v);
        }

        //创建表格
        table = new JTable(CellsVector,TitleVector);
        table.getColumnModel().getColumn(0).setPreferredWidth(60);
        table.getColumnModel().getColumn(0).setMaxWidth(60);
        table.getColumnModel().getColumn(0).setMinWidth(60);
        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
        r.setHorizontalAlignment(JLabel.CENTER);
        r.setBackground(Color.LIGHT_GRAY);

        DefaultTableCellRenderer r1 = new DefaultTableCellRenderer();
        r1.setHorizontalAlignment(JLabel.CENTER);


        table.getColumnModel().getColumn(0).setCellRenderer(r);
        table.getColumnModel().getColumn(1).setCellRenderer(r1);
        table.getColumnModel().getColumn(2).setCellRenderer(r1);
        table.getColumnModel().getColumn(3).setCellRenderer(r1);
        table.getColumnModel().getColumn(4).setCellRenderer(r1);
        //滚动面板
        JScrollPane scrollPane = new JScrollPane(table);
        //将滚动面板插入到窗体的内容面板中
        this.add(scrollPane,new BorderLayout().CENTER);
    }

    @Override
    public void run() {
        while (true) {
            //每隔1秒钟更新JTable
            table.validate();
            table.updateUI();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
